//
//  YZXComposeController.swift
//  YZXWeibo
//
//  Created by 叶周翔 on 16/7/28.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit
import SVProgressHUD

class YZXComposeController: UIViewController,UITextViewDelegate {
    /**
     *  是否显示照片选择器的标记
     */
    private var isShowPicker:Bool = false
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private let maxLength = 140
    
    //MARK:view的生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUpUI()
        // 设置导航
        self.setupNav()
        // 添加图片选择器
        self.setupImageSelect()
        
        // 监听键盘的弹出和退出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 没有照片选择器的时候弹出键盘
        if !self.isShowPicker {
            // 弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    // 设置UI
    private func setUpUI(){
        self.view.addSubview(textView)
        self.view.addSubview(toolBar)
        
        
        /**
        *  闭包的回调
        */
        toolBar.barButtonItemCallback = { (btn:UIBarButtonItem) -> Void in
            
            //TODO:
            switch btn.tag{
            case 0:
                // 弹出图片选择控制器
                self.photoSelectorVC.view.snp_updateConstraints(closure: { (make) -> Void in
                    make.bottom.equalTo(self.view).offset(0)
                })
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.view.layoutIfNeeded()
                })
                self.textView.resignFirstResponder()
                // 修改标记
                self.isShowPicker = true
                
            case 1:
                print("#")
            case 2:
                print("@")
            case 3:
                // 切换表情键盘
                self.exchangeEmojiKeyboard(btn)
            case 4:
                print("+")
            default:
                print("并没有")
            }
        }
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
        }
    }
    
    // 设置图片选择器
    private func setupImageSelect() {
    
        let photoSelectorView = photoSelectorVC.view
        
        self.view.addSubview(photoSelectorView)
        // 当一个控制器的view成为别的控制器的子view的时候  这个控制器也要成为控制器的子控制器 这样子事件不会断
        self.addChildViewController(photoSelectorVC)
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            let height = UIScreen.mainScreen().bounds.size.height * 0.6
            make.leading.trailing.equalTo(self.view)
            make.height.equalTo(height)
            make.bottom.equalTo(self.view).offset(height)
        }
        
    }
    //MARK:- 切换表情键盘
    private func exchangeEmojiKeyboard(btn:UIBarButtonItem) {
        textView.resignFirstResponder()
        let keyIntputView:UIView? = textView.inputView == nil ? emoticonKeyboard : nil
        textView.inputView = keyIntputView
//        var image: String
//        if inputView == nil {
//            image = "compose_keyboardbutton_background"
//        }else{
//            image = "compose_emoticonbutton_background"
//        }
//        btn.setImage(UIImage(named: image), forState: UIControlState.Normal)
//        btn.setImage(UIImage(named: image + "_highlighted"), forState: UIControlState.Highlighted)
        
        // 延迟0.25秒弹出
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            // 再弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    
    
    //关闭控制器
    @objc private func close() {
        SVProgressHUD.dismiss()
        self.textView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
        // 发送微博
        let text = textView.emoticonText()
        if text.characters.count > maxLength {
            SVProgressHUD.showErrorWithStatus("文字超出了长度")
            return
        }
        // 普通用户只能发送一张图片
        let sendImage = photoSelectorVC.photos.first
        
        // 没有超出长度 发送微博
        SVProgressHUD.showWithStatus("正在发送微博")
        
//        YZXStatusViewModel.shareStatusVM.sendStatus(text) { (error) -> Void in
//            
//            if error != nil {
//                SVProgressHUD.showErrorWithStatus("发送微博失败")
//            }
//        }
        
        YZXStatusViewModel.shareStatusVM.sendStatus(text, image: sendImage) { (error, progress) -> Void in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    SVProgressHUD.dismiss()
                })
                
                return
            }
            
//            let pro:Int64 = progress!.completedUnitCount
            
//            SVProgressHUD.showProgress(Float(pro))
            
        }
        
        SVProgressHUD.showSuccessWithStatus("微博发送成功")
        
        // 延时关闭
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
        
    }
    
    //MARK: 设置导航
    private func setupNav() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        // 右边按钮不可以用
        navigationItem.rightBarButtonItem?.enabled = false
        
        self.setTitle()
    }
    
    // 设置导航的title
    private func setTitle() {
        
        let prefex = "发微博"
        if let screen_name = YZXUserAccountVM.shareUserAccountVM.userAccount?.screen_name{
            
            let content = prefex + "\n" + screen_name
            
            let titleLabel = UILabel()
            
            titleLabel.font = UIFont.systemFontOfSize(14)
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = NSTextAlignment.Center
            
            let att = NSMutableAttributedString(string: content)
            // 需要给文字添加属性的文字范围
            let range = (content as NSString).rangeOfString(screen_name)
            att.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: UIColor.lightGrayColor()], range: range)
            
            //设置属性的文本
            titleLabel.attributedText = att
            titleLabel.sizeToFit()
            
            self.navigationItem.titleView = titleLabel
        }else{
            self.navigationItem.title = prefex
        }
        
    }
    
    
    
    //MARK:键盘的监听方法
    @objc private func willChangeFrame(notification:NSNotification){
        let duration:NSTimeInterval = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 键盘最终的位置
        let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 计算toolbar最终的位置
        let bottomValue = -(screenHeight - endFrame.origin.y)
        // 更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(bottomValue)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    /// 自定义的表情键盘的view
    private lazy var emoticonKeyboard: YZXEmojticonKeyboard = {
        let keyboard = YZXEmojticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    private lazy var textView:YZXTextView =  {
       let textview = YZXTextView()
        textview.placeholder = "输入微博内容..."
        textview.delegate = self
        textview.font = UIFont.systemFontOfSize(14)
        // 可以滚动
        textview.scrollEnabled = true
        textview.alwaysBounceVertical = true
        textview.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return textview
    }()
    
    private lazy var toolBar:YZXToolbar = YZXToolbar()
    
    private lazy var photoSelectorVC: YZXPhotoPickerController = {
       let pvc = YZXPhotoPickerController()
        pvc.sendBtnBeUse = { () -> Void in
            self.navigationItem.rightBarButtonItem?.enabled = true
        }
        return pvc
    }()
    
}

extension YZXComposeController {
    // 代理方法
    func textViewDidChange(textView: UITextView) {
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    
}